import requests
import re
from urllib import parse
from win32com.client import Dispatch
import time
import win32api
import pyperclip
from DownloadMovie import download


class dytt(object):
    def __init__(self):
        pass

    @staticmethod
    def get_id():
        name = parse.quote(input("请输入你要下载的电影名称："), encoding='gbk')
        url = "http://s.ygdy8.com/plus/so1.php?typeid=1&keyword=" + name
        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            "Cookie": "UM_distinctid=16f9ecd77256b4-07ee71ccac26da-376b4502-1fa400-16f9ecd77262a1",
            "Host": "s.ygdy8.com",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36",
        }
        r = requests.get(url, headers=headers, verify=False)
        r.encoding = 'gbk'
        # print(r.text)
        result1 = re.findall("<a href='/html/gndy/.+?</a>", r.text, re.S)
        # print(result1)
        if len(result1) == 0:
            print("未获取到资源~正在切换路线寻找资源···")
            names = parse.unquote(name, encoding='gbk')
            # print(names)
            download(names)
            time.sleep(3)
            quit()
        elif len(result1) == 1:
            result2 = str(re.findall("html/gndy/.+?.html", str(result1), re.S)).strip('[""]').strip("'")
            # print(result2)
            return result2
        else:
            for i in range(len(result1)):
                print(f"{i + 1}、", result1[i].strip("<a href=</a>"))
                i += 1
            num = int(input("请输入你要下载的电影序号："))
            result2 = str(re.findall("html/gndy/.+?.html", result1[num - 1], re.S)).strip('[""]').strip("'")
            # print(result2)
            return result2

    @staticmethod
    def get_download_url():
        movie_id = dytt.get_id()
        requests.packages.urllib3.disable_warnings()
        url = "https://www.ygdy8.com/" + movie_id
        # print(url)
        r = requests.get(url, verify=False)
        r.encoding = 'gbk'
        # print(r.text)
        result = re.findall('>magnet:.+?<', r.text, re.S)
        # print(len(result))
        if len(result) == 0:
            result1 = re.findall('<a href="ftp:.+?">', r.text, re.S)
            if len(result1) == 0:
                result3 = re.findall('thunder.+?<', r.text, re.S)
                if len(result3) == 0:
                    print("暂未找到下载链接或下载链接失效！")
                elif len(result3) == 1:
                    print("正在打开迅雷，可能需要几秒钟~")
                    win32api.ShellExecute(0, 'open', 'C:\\Program Files\\Thunder\\Program\\ThunderStart.exe', '', '', 3)
                    time.sleep(5)
                    pyperclip.copy(result3)
                else:
                    for j in range(len(result3)):
                        print(f"{j + 1}、", result3[j])
                        j += 1
                    num = int(input("请选择："))
                    pyperclip.copy(result3[num - 1])
            else:
                if len(result1) == 1:
                    result2 = str(result1).strip("['<a href=>']").strip('"')
                    # print(result2)
                    dytt.open_thunder(result2)
                else:
                    for m in range(len(result1)):
                        print(f"{m + 1}、", result1[m])
                        m += 1
                    num = int(input("请选择："))
                    result2 = str(result1[num - 1]).strip("['<a href=>']").strip('"')
                    # print(result2)
                    dytt.open_thunder(result2)
        else:
            for n in range(len(result)):
                print(f"{n + 1}、", result[n].strip('><'))
                n += 1
            num = int(input("请输入你要下载的电影序号："))
            result3 = result[num - 1].strip('><')
            dytt.open_thunder(result3)

    def open_thunder(downloadurl):
        print("正在打开迅雷，可能需要几秒钟~")
        win32api.ShellExecute(0, 'open', 'C:\\Program Files\\Thunder\\Program\\ThunderStart.exe', '', '', 3)
        time.sleep(5)
        thunder = Dispatch('ThunderAgent.Agent64.1')
        thunder.AddTask(downloadurl)
        thunder.CommitTasks()


dytt.get_download_url()
